<?php
/*
 * Created on 12-05-2012
 */

class DataGeneratorsController extends AppController {
	/**
 * Controller name
 *
 * @var string
 */
	public $name = 'DataGenerators';

/**
 * Default helper
 *
 * @var array
 */
	public $helpers = array();
	public $ile;

/**
 * This controller does not use a model
 *
 * @var array
 */
	public $uses = array('Court', 'Reservation', 'FieldType',  'User', 'DataGenerator');
	
	// Zmienne potrzebne do generacji danych
	protected $users = array(
		'names'		=> array(
			'male'		=> array(
				'Łukasz', 'Wojciech', 'Tomasz', 'Paweł', 'Michał', 'Mateusz', 'Maciej', 'Zbigniew',
				'Szymon', 'Maksymilian', 'Piotr', 'Bartosz', 'Marcin', 'Cezary', 'Pankracy', 'Tymoteusz',
			),
			'female'	=> array(
				'Anna', 'Joanna', 'Ewa', 'Monika', 'Kamila', 'Agnieszka', 'Alicja', 'Ilona', 'Gertruda',
				'Ela', 'Jagoda', 'Marta', 'Martyna', 'Ola', 'Ula', 'Hipolita',
			),
		),
		'surnames'	=> array(
			'male'		=> array(
				'Tusk', 'Kaczyński', 'Palikot', 'Rywin', 'Marcinkiewicz', 'Gosiewski', 'Kowalski', 'Malinowski',
				'Stokarczyk', 'Lato', 'Bruzda', 'Drozda', 'Michnik', 'Miller', 'Meller',
			),
			'female'	=> array(
				'Tusk', 'Rogal', 'Buła', 'Pigwa', 'Szelmowska', 'Kowalska', 'Malinowska', 'Stańczyk', 'Gessler',
				'Tracka', 'Pulchna', 'Kot', 'Tokarska', 'Stoch', 'Kubica', 'Turyn'
			),
		),
		'addresses'	=> array(
			'street'	=> array(
				'ul. Dowborczyków', 'ul. Getta Żydowskiego', 'ul. Nałkowskich', 'ul. Gliniana', 'al. Jana Pawła II',
				'Stary Rynek Oliwski', 'ul. Piotrkowska', 'ul. Obywatelska', 'Stary Kadłub', 'ul. Czerniakowska',
				'ul. Pabianicka', 'ul. Więckowskiego', 'ul. Toruńska', 'ul. Plebiscytowa'
			),
			'number'	=> array(
				'17/19', '24 b', '118', '63 a', '50', '5', '22c', '122m.7', 'III', '28'
			),
		),
		'cities'	=> array(
			'Kielce', 'Kraków', 'Warszawa', 'Toruń', 'Lublin', 'Malbork', 'Łódź', 'Katowice', 'Wrocław', 'Wałbrzych',
			'Lubicz', 'Tymbark', 'Krosno', 'Wola Osowa', 'Staszów', 'Książ', 'Bar', 'Łomża', 'Żywiec', 'Suków'
		),
		'usernames'	=> array(
			'prefix'	=> array(
				'Raczy', 'Chyzy', 'Boska', 'Skoczna', 'Pyszny', 'Dumny', 'Smieszna', 'Cudna', 'Doom'
			),
			'suffix'	=> array(
				'Biegacz', 'Konik', 'Strzala', 'Wiewiora', 'Obiad', 'Paw', 'Opowiastka', 'Balou', 'Thrower'
			),
		)
	);
	protected $fieldTypes = array(
		'trawa',
		'żwir',
		'beton',
		'guma',
		'kamień',
		'stal',
		'drewno',
	);
	protected $courts = array(
		'first'		=> array(
			'Miejski', 'Okręgowy', 'KS', 'Wydziałowy', 'Międzyszkolny', 'Wojskowy'
		),
		'second'	=> array(
			'oddział', 'kort', 'lokal', 'budynek',
		),
		'third'		=> array(
			'"ZSHH Bieżanów"', 'spółdzielniany', 'w Rabce', '"Polo-coCta"'
		),
	);
	
	public function isAuthorized($user) {
		if (in_array($user['role'], array('admin', 'superAdmin'))) {
			return true;
		}
		return false;
	}
	
	public function index() {
		$this->set('title_for_layout', 'Generator danych');
		if(!empty($this->data)) {
			// Generujemy:
				// Użytkowników
            if(isset($this->data['DataGeneratorUser'])) {
            	$this->loadModel('DataGeneratorUser');
		    	$this->DataGeneratorUser->set($this->data);
				$this->DataGeneratorUser->setValidate();
		    	
		        $howMany = $this->data['DataGeneratorUser']['howMany'];
            	$this->generateUsers($howMany);
            } else 
				// Typy kortów
            if(isset($this->data['DataGeneratorFieldType'])) {
            	$this->generateFieldTypes();
            } else 
				// Korty
            if(isset($this->data['DataGeneratorCourt'])) {
                $this->loadModel('DataGeneratorCourt');
		    	$this->DataGeneratorCourt->set($this->data);
				$this->DataGeneratorCourt->setValidate();
				
				$howMany = $this->data['DataGeneratorCourt']['howMany'];
            	$this->generateCourts($howMany);
            } else 
				// Rezerwacje
            if(isset($this->data['DataGeneratorReservation'])) {
                $this->loadModel('DataGeneratorReservation');
		    	$this->DataGeneratorReservation->set($this->data);
				$this->DataGeneratorReservation->setValidate();
				
				$howMany = $this->data['DataGeneratorReservation']['howMany'];
            	$this->generateReservations($howMany);
            } 
        } 
	}
	
	private function generateUsers($howMany = 1) {
		$howMany = ($howMany < 1000) ? $howMany : 1000;
		$usersToBeGenerated = array();
		for($i=0; $i<$howMany; $i++) {
			$gender = (rand()%2==0) ? 'male' : 'female';
			$name = $this->users['names'][$gender][rand(0, count($this->users['names'][$gender])-1)];
			$postal_code = rand(10, 99).'-'.rand(100, 999);
			$surname = $this->users['surnames'][$gender][rand(0, count($this->users['surnames'][$gender])-1)];
			$address = $this->users['addresses']['street'][rand(0, count($this->users['addresses']['street'])-1)]." ".$this->users['addresses']['number'][rand(0, count($this->users['addresses']['number'])-1)];
			$city = $this->users['cities'][rand(0, count($this->users['cities'])-1)];
			$username =  $this->users['usernames']['prefix'][rand(0, count($this->users['usernames']['prefix'])-1)].$this->users['usernames']['suffix'][rand(0, count($this->users['usernames']['suffix'])-1)].rand(10000,50000);
			$email = $username.'@korty.pl';
			$phone = rand(100, 999).'-'.rand(100, 999).'-'.rand(100, 999);
			
			array_push($usersToBeGenerated, array(
				'name'			=> $name,
				'surname'		=> $surname,
				'address'		=> $address,
				'postal_code'	=> $postal_code,
				'city'			=> $city,
				'email'			=> $email,
				'phone'			=> $phone,
				'activated'		=> (rand()%2),
				'username'		=> $username,
				'password'		=> 'ala123',
				'cpassword'		=> 'ala123'
			));
		}
		if($this->User->saveAll($usersToBeGenerated)) {
			$this->Session->setFlash('Wygenerowano '.$howMany.' użytkowników.', 'flash_success');
		} else {
			$this->Session->setFlash('Błąd generacji użytkowników.', 'flash_failure');
		}
	}
	private function generateFieldTypes() {
		$fieldTypesToBeGenerated = array();
		for($i=0; $i<count($this->fieldTypes); $i++) {
			$name = $this->fieldTypes[$i];
			array_push($fieldTypesToBeGenerated, array(
				'name'			=> $name,
			));
		}
		if($this->FieldType->saveAll($fieldTypesToBeGenerated)) {
			$this->Session->setFlash('Wygenerowano '.count($this->fieldTypes).' typów kortów.', 'flash_success');
		} else {
			$this->Session->setFlash('Błąd generacji typów kortów.', 'flash_failure');
		}
	}
	private function generateCourts($howMany = 1) {
		$howMany = ($howMany < 1000) ? $howMany : 1000;
		$courtsToBeGenerated = array();
		$fieldTypeIds = array_values($this->FieldType->find('list', array('fields' => 'FieldType.id')));
		if(empty($fieldTypeIds)) {
			$this->Session->setFlash('Brak typów kortów - nie można wygenerować kortów.', 'flash_failure');
		} else {
			for($i=0; $i<$howMany; $i++) {
				$name = $this->courts['first'][rand(0, count($this->courts['first'])-1)]." ".
					$this->courts['second'][rand(0, count($this->courts['second'])-1)]." ".
					$this->courts['third'][rand(0, count($this->courts['third'])-1)];
				array_push($courtsToBeGenerated, array(
					'field_type_id' => $fieldTypeIds[rand(0, count($fieldTypeIds)-1)],
					'name' => $name,
					'covered' => (rand(0,15)%2),
					'out_of_order' => (0),
					'start_time' => date("H:i:s", mktime(rand(7, 12), 0, 0)),
					'end_time' => date("H:i:s", mktime(rand(16, 22), 0, 0))
				));
			}
			if($this->Court->saveAll($courtsToBeGenerated)) {
				$this->Session->setFlash('Wygenerowano '.$howMany.' kortów.', 'flash_success');
			} else {
				$this->Session->setFlash('Błąd generacji kortów.', 'flash_failure');
			}
		}
	}
	private function generateReservations($howMany = 1) {
		$howMany = ($howMany < 1000) ? $howMany : 1000;
		$availableStartTimes = $this->Court->getAvailableStartTimes();
		
		$userIds = array_values($this->User->find('list', array(
			'fields'		=> 'User.id',
			'conditions'	=> array('User.activated' => '1')
		)));
		$courtIds = array_values($this->Court->find('list', array(
			'fields'		=> 'Court.id',
			'conditions'	=> array('Court.out_of_order' => '0')
		)));
		
		$reservationsToBeGenerated = array();
		for($i=0; $i<$howMany; $i++) {
			$done = false;
			while(!$done) {
				$courtId = $courtIds[rand(0, count($courtIds)-1)];
				$dateTime = date("Y-m-t", mktime(0, 0, 0, date("m"), date("d")+rand(1, 365), date("y")));
				
				$availableStartTimes = $this->Court->getAvailableStartTimes($courtId, $dateTime);
				if(!empty($availableStartTimes)) {
					$startTimeValues = array_values($availableStartTimes);
					$startTime = $startTimeValues[rand(0, count($startTimeValues)-1)];
					$done = true;
				}
			}
			$courtId = $courtIds[rand(0, count($courtIds)-1)];
			array_push($reservationsToBeGenerated, array(
				'user_id' => $userIds[rand(0, count($userIds)-1)],
				//'tournament_id' => null,		TODO: Generacja turniejów/cyklicznych
				'court_id' => $courtIds[rand(0, count($courtIds)-1)],
				'start_time' => $dateTime.' '.$startTime,
			));
		}

		if($this->Reservation->saveAll($reservationsToBeGenerated)) {
			$this->Session->setFlash('Wygenerowano '.$howMany.' rezerwacji.', 'flash_success');
		} else {
			$this->Session->setFlash('Błąd generacji rezerwacji.', 'flash_failure');
		}
	}
}
?>
